//
//  HMPictureBrowserController.swift
//  MicroBlog
//
//  Created by QT on 15/8/8.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit
import SVProgressHUD
private let HMPictureBrowserCell = "HMPictureBrowserCell"
class HMPictureBrowserController: UIViewController{

    // 定义变量，接收图片url和indexpath
    var urls: [NSURL]
    var index: Int
    
    init(urls: [NSURL],index: Int){
        self.urls = urls
        self.index = index
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.blackColor() 
        // Do any additional setup after loading the view.
        

    }

    
    override func loadView() {
        var screenSize = UIScreen.mainScreen().bounds
        screenSize.size.width += 20
        view = UIView(frame: screenSize)
        
        setUpUI()
    }
    
    // 跳转操作一定不要再这个方法执行
//    override func viewDidAppear(animated: Bool) {
//        let ind = NSIndexPath(forItem: index, inSection: 0)
//        picView.scrollToItemAtIndexPath(ind, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
//    }
    override func viewWillAppear(animated: Bool) {
        let ind = NSIndexPath(forItem: index, inSection: 0)
        picView.scrollToItemAtIndexPath(ind, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    // MARK: - 按钮点击事件
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func save(){
        // 获取当前正在像是的图片
        let cell = picView.visibleCells().last as! HMPictureViewCell
        let img = cell.currentPic
        
//        UIImageWriteToSavedPhotosAlbum(img!, nil, nil, nil)
        UIImageWriteToSavedPhotosAlbum(img!, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
//    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    @objc private func image(image: UIImage,didFinishSavingWithError error: NSError?,contextInfo: AnyObject?){
        // 保存完成
        SVProgressHUD.showInfoWithStatus("保存完成")
    }
    
    private func setUpUI(){
        // 添加控件
        view.addSubview(picView)
        
        picView.dataSource = self
        
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        // 布局
        closeBtn.translatesAutoresizingMaskIntoConstraints = false
        saveBtn.translatesAutoresizingMaskIntoConstraints  = false
        picView.translatesAutoresizingMaskIntoConstraints = false
        // picView 约束
        let dict = ["pic": picView,"close":closeBtn,"save":saveBtn]
        
        
        // 设置CollectionView 与根视图相同大小
        picView.frame = view.bounds
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[pic]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[pic]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        // 按钮约束 ---> 竖直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[close(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[save(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        // 按钮约束 ---> 水平方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[close(88)]-(>=0)-[save(88)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        // MARK: - 设置控件属性
           // 注册cell 
        picView.registerClass(HMPictureViewCell.self, forCellWithReuseIdentifier: HMPictureBrowserCell)
        
           // 按钮添加点击事件
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
           // 设置布局
        let layout = picView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        picView.pagingEnabled = true
        picView.showsHorizontalScrollIndicator = false
        picView.showsVerticalScrollIndicator = false
    }

    // MARK: -懒加载
    private lazy  var closeBtn: UIButton = UIButton(title: "关闭", BGColor: UIColor.darkGrayColor())
    private lazy  var saveBtn: UIButton = UIButton(title: "保存", BGColor: UIColor.darkGrayColor())
    private lazy  var picView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
}

// MARK: - 数据源方法

extension HMPictureBrowserController: UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMPictureBrowserCell, forIndexPath: indexPath) as! HMPictureViewCell
        
//        cell.backgroundColor = UIColor.randomColor()
        // 获取url
        let url = urls[indexPath.row]
        cell.url = url
        
        // 设置代理
        cell.pictureDelegate = self
        
        return cell
    }
}
private var photoScale: CGFloat = 1
// MARK: - cell的代理方法实现
extension HMPictureBrowserController: HMPictureCellDelegate{
    func pictureViewScale(scale: CGFloat) {
//        print(scale)
        // 保存缩放
        photoScale = scale
        // 设置其他控件是否隐藏
        hiddenControlls(scale<1)
        // 
        if scale < 1{
            // 交互转场
            startInteractiveTransition(self)
        }else{
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
        }
    }
    
    
    // 是否隐藏"保存""关闭"按钮
    func hiddenControlls(hidden: Bool){
        closeBtn.hidden = hidden
        saveBtn.hidden = hidden
        picView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()

    }
}

extension HMPictureBrowserController: UIViewControllerInteractiveTransitioning{
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        view.alpha = photoScale
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
    }
}
extension HMPictureBrowserController: UIViewControllerContextTransitioning{
   // 结束转场
    func completeTransition(didComplete: Bool){
       dismissViewControllerAnimated(true, completion: nil)
    }
    
    func containerView() -> UIView?{return view}
    
    func isAnimated() -> Bool{return true}
    
    func isInteractive() -> Bool {return true}
    
    func transitionWasCancelled() -> Bool {return true}
    
    func presentationStyle() -> UIModalPresentationStyle{
        return UIModalPresentationStyle.Custom
    }

    func updateInteractiveTransition(percentComplete: CGFloat){}
    func finishInteractiveTransition(){}
    func cancelInteractiveTransition(){}
    
    
    func viewControllerForKey(key: String) -> UIViewController?{
        return self
    }

    func viewForKey(key: String) -> UIView?{ return view}

    func targetTransform() -> CGAffineTransform{ return CGAffineTransformIdentity}
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect{ return CGRectZero}
    
    func finalFrameForViewController(vc: UIViewController) -> CGRect{ return CGRectZero}

}
